package com.xiaolei.library.Net.RetrofitExt.factorys;

import androidx.lifecycle.LiveData;

import com.xiaolei.library.Net.RetrofitExt.adapters.LiveDataCallAdapter;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import retrofit2.CallAdapter;
import retrofit2.Response;
import retrofit2.Retrofit;

public class LiveDataCallAdapterFactory extends CallAdapter.Factory
{
    @Override
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit)
    {
        Type responseType = null;
        if (CallAdapter.Factory.getRawType(returnType) != LiveData.class)
        {
            return null;
        }

        Type observableType = CallAdapter.Factory.getParameterUpperBound(0, (ParameterizedType) returnType);
        Class rawObservableType = CallAdapter.Factory.getRawType(observableType);
        if (rawObservableType == Response.class)
        {
            if (observableType instanceof ParameterizedType)
            {
                responseType = CallAdapter.Factory.getParameterUpperBound(0, (ParameterizedType) observableType);
            }
        } else
        {
            responseType = observableType;
        }
        return new LiveDataCallAdapter(responseType);
    }
}
